﻿using Company.Core.Attributes;
using Company.Core.Config;
using Company.Core.Extensions;
using Company.Core.Helpers;
using DynamicData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Core.Cache
{
    /// <summary>
    /// 缓存实现子类
    /// </summary>
    [ExposedService(interfaces: typeof(ICacheManager))]
    internal class CacheManager : ICacheManager
    {
        private readonly IConfigManager _config;
        private readonly Dictionary<string, string> _cache = new Dictionary<string, string>();
        public CacheManager(IConfigManager configManager)
        {
            _config = configManager;
            _cache = configManager.Read<Dictionary<string, string>>(ConfigKeys.CacheConfig) ?? new();
        }

        public T Get<T>(ValueType key)
        {
            Assert.NotNull(key);
            if (_cache.ContainsKey(key.ToString()))
            {
                var json = _cache[key.ToString()];
                return JsonHelper.ToObject<T>(json);
            }

            return default;
        }

        public void Set<T>(ValueType key, T value)
        {
            var json = JsonHelper.ToJson(value);
            var name = key.ToString();
            if (_cache.ContainsKey(name))
            {
                _cache[name] = json;
            }
            else
            {
                _cache.Add(name, json);
            }

            Save();
        }

        public void Delete(ValueType key)
        {
            var name = key.ToString();
            if (_cache.ContainsKey(name))
            {
                _cache.Remove(name);
                Save();
            }
        }

        private void Save()
        {
            _config.Write(ConfigKeys.CacheConfig, _cache);
        }
    }
}
